<template>
  <div class="officerManage">
    <div class="list-search">
      <div class="singe-search">
        <el-cascader v-model="searchForm.deptIdArr" :options="deptTree" :props="defaultProps" clearable="true"
          @change="handleDeptChange"></el-cascader>
      </div>
      <div class="singe-search">
        <el-input v-model.trim="searchForm.realName" placeholder="请输入想要搜索的姓名/账号" clearable></el-input>
      </div>
      <div class="singe-search-btn">
        <el-button class="singe-search-btn1" @click="getOfficerList(1)">搜索</el-button>
        <el-button class="singe-search-btn2" @click="resetForm">重置</el-button>
      </div>
      <div class="singe-search-btn save-btn">
        <el-button class="singe-search-btn1" @click="handlerSave">新增</el-button>
        <el-button class="singe-search-btn2" @click="handleImport">导入</el-button>
      </div>
    </div>
    <el-dialog title="警员数据导入" append-to-body :visible.sync="excelBox" width="720px">
      <avue-form :option="excelOption" v-model="excelForm" :upload-after="uploadAfter">
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
    <div class="table-main">
      <el-table :data="tableData" style="width: 100%" :height="tableHeight">
        <el-table-column type="index" label="序号" width="70" align="center"></el-table-column>
        <el-table-column prop="code" label="警号" min-width="120" align="center">
        </el-table-column>
        <el-table-column prop="deptName" label="所属部门" min-width="180" align="center">
        </el-table-column>
        <el-table-column prop="realName" label="姓名" min-width="80" align="center">
        </el-table-column>
        <el-table-column prop="roleName" label="所属角色" min-width="80" align="center">
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="120" align="center">
        </el-table-column>
        <el-table-column label="操作" min-width="120" align="center">
          <template slot-scope="scope" v-if="scope.row.account != 'admin'">
            <el-button class="resetBtn" @click="updatePwd(scope.row)" type="text" size="small">重置密码</el-button>
            <span class="partition">|</span>
            <el-button class="editBtn" @click="handleEdit(scope.row)" type="text" size="small">编辑</el-button>
            <span class="partition">|</span>
            <el-button class="deleteBtn" @click="handleDelete(scope.row)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="pageForm.pageNum" :page-sizes="[10, 20, 50, 100]" :page-size="pageForm.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="pageForm.total">
        </el-pagination>
      </div>
    </div>
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="728px" :append-to-body="true">
      <div class="deleteDiv" v-if="isDelete">
        <img class="icon" src="../../img/images/template/tip_red.png" />
        <span class="text">是否确认删除当前警员？</span>
      </div>
      <el-form :model="form" :rules="rules" ref="form" label-width="100px" label-position="top" v-else>
        <el-form-item label="警号：" prop="code">
          <span class="tip">(最多20字符，初始的密码为 123456)</span>
          <el-input v-model="form.code" placeholder="请输入警号"></el-input>
        </el-form-item>
        <el-form-item label="姓名：" prop="realName">
          <el-input v-model="form.realName" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="所属部门：" prop="deptId">
          <el-cascader v-model="form.deptIdArr" :options="deptTree" :props="defaultProps" clearable="true"
            @change="handleDeptChange" placeholder="请选择部门"></el-cascader>
        </el-form-item>
        <el-form-item label="角色：" prop="roleId">
          <el-select v-model="form.roleId" placeholder="请选择角色">
            <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="officerHandler">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getDeptTreeAuth
  } from '../../api/system/dept.js'
  import {
    getList,
    add,
    update,
    remove,
    resetPassword
  } from '../../api/system/user.js'
  import {
    getList as getRoleList
  } from '../../api/system/role.js'

  import {
    mapGetters
  } from "vuex";
  import {
    getToken
  } from '@/util/auth';
  export default {
    data() {
      return {

        excelBox: false,

        excelForm: {},
        excelOption: {
          submitBtn: false,
          emptyBtn: false,
          column: [{
              label: '模板上传',
              prop: 'excelFile',
              type: 'upload',
              drag: true,
              loadText: '模板上传中，请稍等',
              span: 24,
              propsHttp: {
                res: 'data'
              },
              tip: '请上传 .xls,.xlsx 标准格式文件',
              action: "/api/blade-user/import-user"
            },
            {
              label: "数据覆盖",
              prop: "isCovered",
              type: "switch",
              align: "center",
              width: 80,
              dicData: [{
                  label: "否",
                  value: 0
                },
                {
                  label: "是",
                  value: 1
                }
              ],
              value: 0,
              slot: true,
              rules: [{
                required: true,
                message: "请选择是否覆盖",
                trigger: "blur"
              }]
            },
            {
              label: '模板下载',
              prop: 'excelTemplate',
              formslot: true,
              span: 24,
            }
          ]
        },


        defaultProps: {
          children: 'children',
          label: 'title',
          value: 'id',
          checkStrictly: true
        },
        searchForm: {
          templateId: '',
          realName: '',
          deptIdArr: [],
          deptId: ''
        },
        pageForm: {
          pageNum: 1,
          pageSize: 20,
          total: 0,
        },
        deptTree: [],
        roleList: [],
        tableData: [],
        dialogVisible: false,
        dialogTitle: '',
        isDelete: false,
        form: {},
        rules: {
          code: [{
            required: true,
            message: '请输入警号',
            trigger: 'blur'
          }, {
            max: 20,
            message: '最多20字符',
            trigger: 'blur'
          }],
          realName: [{
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
          }],
          deptId: [{
            required: true,
            message: '请选择部门',
            trigger: 'blur'
          }],
          roleId: [{
            required: true,
            message: '请选择角色',
            trigger: 'blur'
          }]
        },
      }
    },
    computed: {
      ...mapGetters(["userInfo"]),
      tableHeight() {
        let h = document.body.clientHeight - 297;
        return h;
      },
    },
    watch: {

      'excelForm.isCovered'() {
        if (this.excelForm.isCovered !== '') {
          const column = this.findObject(this.excelOption.column, "excelFile");
          column.action = `/api/blade-user/import-user?isCovered=${this.excelForm.isCovered}`;
        }
      }
    },
    mounted() {
      this.getRoleList();
      this.getDeptTree();
      this.getOfficerList(1);
    },
    methods: {
      handleTemplate() {
        window.open(`/api/blade-user/export-template?${this.website.tokenHeader}=${getToken()}`);
      },
      handleImport() {
        this.excelBox = true;
      },
      uploadAfter(res, done, loading, column) {
        this.excelBox = false;
        this.refreshChange();
        done();
      },
      refreshChange() {
        this.getOfficerList(this.pageForm.pageNum);
      },
      updatePwd(row) {
        this.$confirm('是否确认重置密码', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          resetPassword(row.id).then(res => {
            if (res.data.code === 200) {
              this.$message({
                message: '重置密码成功',
                type: 'success'
              });
            } else {
              this.$message({
                message: '重置密码失败',
                type: 'error'
              });
            }
          })
        })
      },
      getRoleList() {
        let that = this;
        getRoleList().then(res => {
          if (res.data.code === 200) {
            that.roleList = res.data.data;
          }
        })
      },
      officerHandler() {
        let that = this;
        if (this.isDelete) {
          remove(this.form.id).then(res => {
            if (res.data.code === 200) {
              that.getOfficerList();
              that.dialogVisible = false;
              this.$message({
                message: '删除成功',
                type: 'success'
              });
            } else {
              this.$message({
                message: '删除失败',
                type: 'error'
              });
            }
          })
        } else {
          this.$refs.form.validate((valid) => {
            if (valid) {
              if (that.form.id) {
                that.form.account = that.form.code;
                update(that.form).then(res => {
                  if (res.data.code === 200) {
                    that.getOfficerList();
                    that.dialogVisible = false;
                    this.$message({
                      message: '编辑警员成功',
                      type: 'success'
                    });
                  } else {
                    this.$message({
                      message: '编辑警员失败',
                      type: 'error'
                    });
                  }
                })
              } else {
                that.form.account = that.form.code;
                that.form.password = '123456';
                add(that.form).then(res => {
                  if (res.data.code === 200) {
                    that.getOfficerList();
                    that.dialogVisible = false;
                    this.$message({
                      message: '新增警员成功',
                      type: 'success'
                    });
                  } else {
                    this.$message({
                      message: '新增警员失败',
                      type: 'error'
                    });
                  }
                })
              }
            }
          })
        }
      },
      handleDelete(row) {
        this.isDelete = true;
        this.dialogTitle = '提示';
        this.form = row;
        this.dialogVisible = true;
      },
      handleEdit(row) {
        this.isDelete = false;
        this.dialogTitle = '编辑-警员';
        this.form = row;
        let parentId = row.deptId;
        this.form.deptIdArr = [parentId];
        let flag = true;
        while (flag) {
          parentId = this.queryParentId(parentId, this.deptTree);
          if (!parentId) {
            break;
          }
          if (parentId !== '1' && parentId !== 1 && parentId !== 0 && parentId !== '0') {
            this.form.deptIdArr.unshift(parentId);
          } else {
            break;
          }
        }
        this.dialogVisible = true;
      },
      queryParentId(id, arr) {
        for (let i = 0, len = arr.length; i < len; i++) {
          if (id === arr[i].id) {
            return arr[i].parentId;
          } else {
            if (arr[i].children) {
              return this.queryParentId(id, arr[i].children);
            }
          }
        }
      },
      handlerSave() {
        this.isDelete = false;
        this.dialogTitle = '新增-警员';
        this.form = {};
        this.dialogVisible = true;
      },
      handleDeptChange(e) {
        if (e && e.length > 0) {
          this.form.deptId = e[e.length - 1];
        } else {
          this.form.deptId = '';
        }
      },
      getDeptTree() {
        let that = this;
        getDeptTreeAuth().then(res => {
          if (res.data.code === 200) {
            that.deptTree = res.data.data;
          }
        })
      },
      getOfficerList(pageNum) {
        let that = this;
        that.searchForm.deptId = that.searchForm.deptIdArr.length > 0 ? that.searchForm.deptIdArr.at(-1) : null
        getList(pageNum, this.pageForm.pageSize, {
          realName: this.searchForm.realName
        }, that.searchForm.deptId).then(res => {
          if (res.data.code === 200) {
            that.tableData = res.data.data.records;
            that.pageForm.total = res.data.data.total
            that.pageForm.pageNum = pageNum
            that.pageForm.pageSize = res.data.data.size
          }
        })
      },
      //清空
      resetForm() {
        this.pageForm.pageNum = 1
        this.searchForm.realName = '';
        this.searchForm.deptIdArr = [];
        this.searchForm.deptId = '';
        this.getOfficerList(this.pageForm.pageNum)
      },
      handleSizeChange(val) {
        this.pageForm.pageSize = val
        this.getOfficerList(1)
      },
      handleCurrentChange(val) {
        this.pageForm.pageNum = val
        this.getOfficerList(val)
      }
    }
  }
</script>

<style scoped lang="scss">
  @import '../../styles/page/list';

  ::v-deep .el-dialog {
    .el-dialog__header {
      height: 46px !important;
      padding: 0 !important;
      margin: 0 40px !important;
      line-height: 46px !important;

      .el-dialog__headerbtn {
        top: 12px !important;
        right: 40px !important;
      }
    }

    .el-dialog__body {
      margin-top: 20px;
      border: 0 !important;
      overflow-y: hidden !important;

      .el-form-item {
        margin-bottom: 0 !important;
      }

      .imgItem {
        margin-bottom: 10px !important;
      }

      .el-cascader {
        width: 100% !important;
      }

      .el-select {
        width: 100% !important;
      }

      .el-upload__tip {
        position: absolute;
        top: 40px;
        left: 370px;
        line-height: 20px;
        width: 160px;
      }

      .el-switch__core {
        border-radius: 20px !important;
      }

      .tip {
        position: absolute;
        top: -40px;
        left: 51px;
        font-size: 14px;
        font-family: PingFang TC-Regular, PingFang TC;
        font-weight: 400;
        color: #959FBA;
      }

      .deleteDiv {
        position: relative;
        width: 100%;
        height: 60px;

        .icon {
          width: 20px;
          height: 20px;
          position: absolute;
          top: 19px;
          left: 0px;
        }

        .text {
          font-size: 16px;
          font-family: PingFang SC-Regular, PingFang SC;
          font-weight: 400;
          color: #000000;
          position: absolute;
          top: 20px;
          left: 30px;
        }
      }
    }

    .el-dialog__footer {
      text-align: center !important;

      .el-button--default {
        padding: 7px 29px !important;
      }

      .el-button--primary {
        padding: 8px 30px !important;
      }
    }
  }

  .officerManage {
    width: 100%;
    height: 100%;
    padding: 0 24px !important;

    .table-main {
      .resetBtn {
        font-size: 14px;
        font-family: PingFang SC-Medium, PingFang SC;
        font-weight: 500;
        color: #2E488B;
      }

      .editBtn {
        font-size: 14px;
        font-family: PingFang SC-Medium, PingFang SC;
        font-weight: 500;
        color: #2E488B;
      }

      .deleteBtn {
        font-size: 14px;
        font-family: PingFang SC-Medium, PingFang SC;
        font-weight: 500;
        color: #EB5757;
      }

      .partition {
        font-size: 14px;
        font-family: PingFang SC-Medium, PingFang SC;
        font-weight: 500;
        color: #C1D3EE;
        margin: 0 10px;
      }
    }

    .list-search {
      width: 100%;
      height: 86px;
      padding: 0px;
    }

    .pagination {
      height: 50px;
    }

    .singe-search {
      width: 296px !important;
      height: 36px !important;
      margin-right: 24px !important;

      ::v-deep .el-input input {
        width: 296px;
        height: 36px;
      }

      ::v-deep .el-select input {
        width: 296px;
        height: 36px;
      }

      ::v-deep .el-cascader input {
        width: 296px;
        height: 36px;
      }
    }

    .singe-search-btn {
      height: 36px !important;

      .singe-search-btn1 {
        width: 88px !important;
        height: 36px !important;
        background: #2E488B !important;
        box-shadow: 0px 1px 1px 0px rgba(123, 144, 176, 0.21) !important;
        border-radius: 4px 4px 4px 4px !important;
        opacity: 1 !important;
        padding: 0 !important;

        font-size: 14px !important;
        font-family: PingFang SC-Regular, PingFang SC !important;
        font-weight: 400 !important;
        color: #FFFFFF !important;
      }

      .singe-search-btn2 {
        width: 88px !important;
        height: 36px !important;
        background: #FFFFFF !important;
        box-shadow: 0px 1px 1px 0px rgba(123, 144, 176, 0.21) !important;
        border-radius: 4px 4px 4px 4px !important;
        opacity: 1 !important;
        border: 1px solid #C1D3EE !important;
        padding: 0 !important;

        font-size: 14px !important;
        font-family: PingFang SC-Regular, PingFang SC !important;
        font-weight: 400 !important;
        color: #2E488B !important;
      }
    }

    .save-btn {
      position: absolute;
      right: 28px;
    }
  }
</style>
